import storage from 'good-storage';

const SEARCH_KEY = '__search__';
const SEARCH_LENGTH = 15;
const HISTORY_KEY = '__historyPlay__';
const PLAY_LENGTH = 15;
const LOVE_KEY = '__love__';
const LOVE_LENGTH = 15;

// 将一个item插入一个list中,以compare为规则确定是否已存在该item,有的话交换至第一项,没有就unshift
function insertArray(item, list, compare, maxLength) {
    const isExist = list.findIndex(compare);
    if (isExist !== -1) {
        [list[0], list[isExist]] = [list[isExist], list[0]];
    } else {
        list.unshift(item);
    }
    if (list.length > maxLength) {
        list = list.slice(0, maxLength);
    }
    return list;
}

export function saveSearchItem(item) {
    let list = storage.get(SEARCH_KEY, []);
    list = insertArray(item, list, i => i.id === item.id, SEARCH_LENGTH);
    storage.set(SEARCH_KEY, list);
    return list;
}

export function deleteSearchItem(item) {
    let list = [];
    if (name) {
        list = storage.get(SEARCH_KEY, []);
        const index = list.findIndex(li => li.id === item.id);
        list.splice(index, 1);
    } else {
        list = [];
    }
    storage.set(SEARCH_KEY, list);
    return list;
}

export function loadSearch() {
    return storage.get(SEARCH_KEY, []);
}

export function saveHistoryPlay(song) {
    let list = storage.get(HISTORY_KEY, []);
    list = insertArray(song, list, i => song.id === i.id, PLAY_LENGTH);
    storage.set(HISTORY_KEY, list);
    return list;
}

export function loadHistoryPlay() {
    return storage.get(HISTORY_KEY, []);
}

export function saveLoveSong(song) {
    let list = storage.get(LOVE_KEY, []);
    list = insertArray(song, list, i => song.id === i.id, LOVE_LENGTH);
    storage.set(LOVE_KEY, list);
    return list;
}

export function removeLoveSong(song) {
    const list = storage.get(LOVE_KEY, []);
    const index = list.findIndex(item => item.id === song.id);
    list.splice(index, 1);
    storage.set(LOVE_KEY, list);
    return list;
}
export function loadLove() {
    return storage.get(LOVE_KEY, []);
}
